import { pluginPath, YamlReader, path } from '#auth'
import fs from 'fs'
import { join } from 'path'
import Yaml from 'yaml'

const configPath = join(path, 'config', 'config', 'other.yaml')
const jsonPath = join(pluginPath, 'data', 'data.json')
if (!fs.existsSync(jsonPath)) fs.writeFileSync(jsonPath, '{}')

let cache = {}
let configCache = {}
getJsonAll()
getConfig('all')
/**
 * 修改或增加一条数据
 * @param {card|group} key 
 * @param {'card'|'group'} keyType 天数
 * @param {{card:string,day:number,group_id?:string,status?:1|2}} data 
 * @param {'add'|'del'|'modify'} type 执行的操作
 */
function setJson(key, keyType, data, type = 'add') {
    switch (type) {
        case 'add':
            if (keyType === 'card') {
                data.status = 0
            }
        case 'modify':
            cache[keyType][key] = data
            break;
        case 'del':
            delete cache[keyType][key]
            break
        default:
            return;
    }
    fs.writeFileSync(jsonPath, JSON.stringify(cache))
    getJsonAll()
}

/**
 * 直接修改json.data
 * @
 */
function setJsonAll(data) {
    fs.writeFileSync(jsonPath, JSON.stringify(data))
    getJsonAll()
}

/**
 * 获得所有数据
 * @returns {{string:{card:string,status:0|1,day:number,group_id:string?}}} 
 */
function getJsonAll() {
    const data = fs.readFileSync(jsonPath, 'utf-8')
    cache = JSON.parse(data)
    return cache
}

/**
 * 根据key获得数据
 * @param {string} key 
 * @param {'card'|'group'} type 
 */
function getJson(key, type = 'card') {
    if (cache[type][key]) return cache[type][key]
    getJsonAll()
    return cache[type][key]
}


/**
 * 增加或删除群黑白名单
 * @param {string|number} group_id 群号
 * @param {'blackGroup'|'whiteGroup'} key 
 * @param {'add'|'del'} type 执行的操作
 */
function setConfig(group_id, key, type = 'add') {
    let yaml = new YamlReader(configPath)
    if (type == 'add') {
        try {
            yaml.addIn(key, group_id)
        } catch (error) {
            yaml.set(key, [group_id])
        }
    } else {
        let index = yaml.jsonData[key].indexOf(group_id)
        yaml.delete(`${key}.${index}`)
    }
    configCache = {}
}

/**
 * 查看黑白名单
 * @param {'blackGroup'|'whiteGroup'} key 
 * @returns 
 */
function getConfig(key) {
    if (configCache[key]) return configCache[key]
    const data = fs.readFileSync(configPath, 'utf-8')
    configCache = Yaml.parse(data)
    return configCache[key]
}

export {
    setJson,
    setJsonAll,
    getJson,
    getJsonAll,
    setConfig,
    getConfig
}